<template>
    <IndependencePage
        ref="independencePage"
        title="活动详情"
        :independence-page-frame="independencePageFrame"
        :independence-page-data="independencePageData"
        class="activity-detail"
    >
        <template #page>
            <page ref="page" v-bind="page" :page-search-data="independencePageData.page" :key="page.key" />
        </template>
    </IndependencePage>
</template>
<script>
import {
    getActivityItemList,
    updateActivityStockLimit,
    getActivityOrders,
    doInvalidActivityProduct
} from '@/api/market/activity'
import ENUMS from '@/enums/activity'
import common from '@/enums/common.js'
import Page from '@/components/Page/index.vue'
import IndependencePage from '@/components/Page/IndependencePage.vue'
import { mapGetters } from 'vuex'
import { msgConfirm } from '@/utils/utils.js'
import auth from './auth.js'
const SAVE_SUCCESS = 'saveSuccess'
export default {
    components: {
        IndependencePage,
        Page
    },
    props: {},
    emits: [SAVE_SUCCESS],
    computed: {
        ...mapGetters(['name'])
    },
    data() {
        return {
            visible: false,
            independencePageData: { page: {} },
            independencePageFrame: [
                {
                    key: 'baseinfo',
                    title: '活动信息',
                    type: 'desc',
                    descs: [
                        {
                            key: 'id',
                            label: '活动id'
                        },
                        {
                            key: 'activityName',
                            label: '活动名称'
                        },
                        {
                            key: 'status',
                            label: '活动状态',
                            frameType: 'tag',
                            tag(data, row) {
                                return ENUMS.STATUS.find((v) => v.id == data)?.tag || ''
                            },
                            render(data) {
                                return ENUMS.STATUS.find((v) => v.id == data)?.text || ''
                            }
                        },
                        {
                            key: 'startTimeString',
                            label: '开始时间'
                        },
                        {
                            key: 'endTimeString',
                            label: '结束时间'
                        }
                    ]
                },
                {
                    title: '商品信息',
                    colon: false,
                    slot: 'page',
                    key: 'page',
                    type: 'slot'
                }
            ],
            page: {
                key: '',
                tableRowKey: (row) => row.productId,
                showToolBar: false,
                beautiful: false,
                isCache: false,
                pageSearchFrame: [
                    {
                        key: 'productId',
                        label: '商品ID',
                        frameType: 'input',
                        style: 'width:200px'
                    }
                ],
                pageTableFrame: [
                    {
                        type: 'expand',
                        frameType: 'table',
                        key: 'expandTable',
                        table: {
                            pageTableFrame: [
                                {
                                    key: 'id',
                                    label: 'id'
                                },
                                {
                                    key: 'status',
                                    label: '状态',
                                    frameType: 'tag',
                                    tag(data, row) {
                                        return ENUMS.ORDER_STATUS.find((v) => v.id == data)?.tag || ''
                                    },
                                    render(data) {
                                        return ENUMS.ORDER_STATUS.find((v) => v.id == data)?.text || ''
                                    }
                                },
                                {
                                    key: 'memberId',
                                    label: '会员id'
                                },
                                {
                                    key: 'orderSn',
                                    label: '订单编号'
                                },
                                {
                                    key: 'payTimeString',
                                    label: '支付时间'
                                }
                            ]
                        },
                        expand: function (row) {
                            return getActivityOrders({
                                activityId: row.activityId,
                                productId: row.productId
                            }).then((v) => {
                                return v.data
                            })
                        }
                    },
                    {
                        label: 'No.',
                        type: 'index'
                    },

                    {
                        label: '商品ID',
                        key: 'productId'
                    },
                    {
                        label: '商品名称',
                        key: 'productName',
                        width: '150px'
                    },
                    {
                        label: '价格',
                        key: 'salePrice'
                    },

                    {
                        label: '是否优惠',
                        key: 'isToUse',
                        render(data) {
                            return common.YESORNO.find((v) => v.value == data)?.label || ''
                        }
                    },
                    {
                        label: '优惠金额',
                        key: 'usePrice'
                    },
                    {
                        label: '库存上限',
                        key: 'stockLimit',
                        width: '150px',
                        separate: '',
                        frameType: (row) =>
                            (this.independencePageData.status == 1 || this.independencePageData.status == 2) &&
                            row.status == 1
                                ? 'mulitiValue'
                                : '',
                        mulitiValue: [
                            { key: 'stockLimit', frameType: 'input', style: 'width:60px' },
                            {
                                key: 'stockLimitButton',
                                style: 'width:60px',
                                frameType: 'buttons',
                                buttons: [
                                    {
                                        functionId: auth.detail,
                                        value: '保存',
                                        icon: 'el-icon-refrigerator',
                                        click: this.saveStockLimit
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        label: '是否参与',
                        key: 'status',
                        frameType: 'tag',
                        tag(data, row) {
                            return ENUMS.PART_IN_STATUS.find((v) => v.id == data).tag || ''
                        },
                        render(data) {
                            return ENUMS.PART_IN_STATUS.find((v) => v.id == data)?.text || ''
                        }
                    },
                    {
                        label: '操作',
                        frameType: 'buttons',
                        buttons: [
                            {
                                functionId: auth.invalid,
                                value: '删除',
                                icon: 'el-icon-delete',
                                click: this.invalid,
                                visible: (row) => {
                                    return (
                                        row.status == 1 &&
                                        (this.independencePageData.status == 1 || this.independencePageData.status == 2)
                                    )
                                }
                            }
                        ]
                    }
                ],
                searchFun: getActivityItemList,
                labelWidth: '80px',
                preSearch: this.preSearch
            }
        }
    },
    methods: {
        invalid(data) {
            this.$confirm(
                '确定删除此活动下的该商品吗?<br><span style="color:red"> 提示：删除后将无法恢复</span>',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    dangerouslyUseHTMLString: true
                }
            )
                .then(() => {
                    return doInvalidActivityProduct({
                        activityId: data.activityId,
                        productId: data.productId,
                        userName: this.name
                    })
                })
                .then((data) => {
                    this.$message({
                        type: 'success',
                        message: '商品删除成功!'
                    })
                    this.$refs.page.onSearch()
                    return Promise.reject()
                })
                .catch((data) => {
                    if (data && data.code == 1) {
                        return this.$confirm(data.message, '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        })
                    }
                    return Promise.reject(data)
                })
                .then(() => {
                    return doInvalidActivityProduct({
                        activityId: data.activityId,
                        productId: data.productId,
                        userName: this.name,
                        confirmFlg: 'true'
                    })
                })
                .then((data) => {
                    this.$message({
                        type: 'success',
                        message: '商品删除成功!'
                    })
                    this.$refs.page.onSearch()
                })
                .catch((data) => {
                    if (typeof data == 'object') {
                        this.$message.error(data.msg || data.message)
                    }
                })
        },
        saveStockLimit(row) {
            let val = row.stockLimit
            var reg = new RegExp('^[0-9]*$')
            if (val && (!reg.test(val) || val.length > 5 || val <= 0 || val > 99999)) {
                this.$message.error('库存上限范围必须是大于0小于等于99999的自然数！')
                return false
            }
            msgConfirm('确定修改此活动下的该商品的库存上限吗?', () => {
                return updateActivityStockLimit({
                    activityId: row.activityId,
                    productId: row.productId,
                    stockLimit: val,
                    userName: this.name
                }).then(() => {
                    this.$message({
                        type: 'success',
                        message: '保存成功!'
                    })
                    this.$refs.page.onSearch()
                })
            })
        },
        preSearch(query) {
            //商品ID
            var productId = query.productId
            if (productId) {
                productId = productId.replace(/，/gi, ',')
                var reg = new RegExp('^[0-9]*$')
                if (!reg.test(productId.replace(/,/g, ''))) {
                    this.$message('商品ID必须是数字！')
                    return false
                }

                var productIdArr = productId.split(',')
                if (productIdArr.length > 20) {
                    this.$message('商品ID最多能同时查询20个！')
                    return false
                }
                for (var i = 0; i < productIdArr.length; i++) {
                    if (productIdArr[i].trim() == '') {
                        this.$message('存在为空的商品ID！')
                        return false
                    }
                }
            }
            return true
        }
    },
    beforeRouteEnter(to, from, next) {
        next((vm) => {
            vm.independencePageData = { page: {} }
            vm.independencePageData.baseinfo = JSON.parse(to.query.data)
            vm.independencePageData.page.activityId = vm.independencePageData.baseinfo.id
            vm.page.key = vm.independencePageData.baseinfo.id
        })
    }
}
</script>
<style lang="scss">
.activity-detail .page-search-form {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}
</style>
